package com.my.test.netty.test;

import java.io.UnsupportedEncodingException;

import com.my.test.netty.NettyServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class Server {

	public static void main(String[] args) {
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();
		try {
			ServerBootstrap bootstrap = new ServerBootstrap();

			bootstrap.group(boss, worker);
			bootstrap.channel(NioServerSocketChannel.class);
			bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel socketChannel)
						throws Exception {
					ChannelPipeline p = socketChannel.pipeline();
					p.addLast("my",new ChannelHandlerAdapter(){
						@Override
						public void channelRead(ChannelHandlerContext ctx, Object msg) {
							ByteBuf buf = (ByteBuf) msg;
							String recieved = NettyServerHandler.getMessage(buf);
							System.out.println("hzb服务器接收到消息：" + recieved);
							try {
								ctx.writeAndFlush(NettyServerHandler.getSendByteBuf("hzb的服务器发送给你的：APPLE"));
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
						}
					});
				}
			});
			ChannelFuture f = bootstrap.bind(8888).sync();
			if (f.isSuccess()) {
				System.out.println("启动Netty服务成功，端口号：" + 8888);
			}
			// 关闭连接
			f.channel().closeFuture().sync();
		} catch (Exception e) {
			System.out.println("启动Netty服务异常，异常信息：" + e.getMessage());
			e.printStackTrace();
		} finally {
			boss.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}
}
